package com.accounting.ui;

import javafx.geometry.Insets;
import javafx.geometry.Pos;
import javafx.scene.control.*;
import javafx.scene.layout.HBox;
import javafx.scene.layout.VBox;
import javafx.scene.layout.GridPane;
import javafx.scene.text.Text;
import javafx.scene.Parent;
import com.accounting.db.DatabaseManager;
import javafx.stage.FileChooser;
import javafx.scene.image.Image;
import javafx.scene.image.ImageView;
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;

public class LoginView {
    private VBox root;
    private TextField usernameField;
    private PasswordField passwordField;
    private Runnable onLoginSuccess;
    private String currentUsername;

    public LoginView() {
        root = new VBox(20);
        root.setPadding(new Insets(40));
        root.setAlignment(Pos.CENTER);
        root.getStyleClass().add("login-view");

        createLoginForm();
    }

    private void createLoginForm() {
        Label titleLabel = new Label("家庭记账系统");
        titleLabel.setStyle("-fx-font-size: 24px; -fx-font-weight: bold;");

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setAlignment(Pos.CENTER);

        usernameField = new TextField();
        usernameField.setPromptText("用户名");
        passwordField = new PasswordField();
        passwordField.setPromptText("密码");

        grid.add(new Label("用户名:"), 0, 0);
        grid.add(usernameField, 1, 0);
        grid.add(new Label("密码:"), 0, 1);
        grid.add(passwordField, 1, 1);

        Button loginBtn = new Button("登录");
        loginBtn.getStyleClass().add("login-button");
        loginBtn.setOnAction(e -> login());

        Button registerBtn = new Button("注册");
        registerBtn.getStyleClass().add("register-button");
        registerBtn.setOnAction(e -> showRegisterDialog());

        HBox buttonBox = new HBox(10);
        buttonBox.setAlignment(Pos.CENTER);
        buttonBox.getChildren().addAll(loginBtn, registerBtn);

        root.getChildren().addAll(titleLabel, grid, buttonBox);
    }

    private void login() {
        String username = usernameField.getText();
        String password = passwordField.getText();

        if (username.isEmpty() || password.isEmpty()) {
            showError("登录失败", "用户名和密码不能为空");
            return;
        }

        if (DatabaseManager.validateUser(username, password)) {
            currentUsername = username;
            if (onLoginSuccess != null) {
                onLoginSuccess.run();
            }
        } else {
            showError("登录失败", "用户名或密码错误");
        }
    }

    private void showRegisterDialog() {
        Dialog<Void> dialog = new Dialog<>();
        dialog.setTitle("用户注册");
        dialog.setHeaderText(null);

        GridPane grid = new GridPane();
        grid.setHgap(10);
        grid.setVgap(10);
        grid.setPadding(new Insets(20));

        TextField usernameField = new TextField();
        PasswordField passwordField = new PasswordField();
        PasswordField confirmPasswordField = new PasswordField();
        TextField nameField = new TextField();
        
        ImageView avatarView = new ImageView();
        avatarView.setFitHeight(100);
        avatarView.setFitWidth(100);
        avatarView.setPreserveRatio(true);
        
        Button chooseImageBtn = new Button("选择头像");
        String[] avatarPath = new String[1];
        
        chooseImageBtn.setOnAction(e -> {
            FileChooser fileChooser = new FileChooser();
            fileChooser.getExtensionFilters().add(
                new FileChooser.ExtensionFilter("图片文件", "*.png", "*.jpg", "*.jpeg")
            );
            File file = fileChooser.showOpenDialog(dialog.getOwner());
            if (file != null) {
                try {
                    // 创建头像存储目录
                    Path avatarsDir = Paths.get("avatars");
                    if (!Files.exists(avatarsDir)) {
                        Files.createDirectory(avatarsDir);
                    }
                    
                    // 复制头像文件到应用目录
                    String fileName = System.currentTimeMillis() + "_" + file.getName();
                    Path targetPath = avatarsDir.resolve(fileName);
                    Files.copy(file.toPath(), targetPath, StandardCopyOption.REPLACE_EXISTING);
                    
                    // 显示头像预览
                    Image image = new Image(file.toURI().toString());
                    avatarView.setImage(image);
                    avatarPath[0] = targetPath.toString();
                } catch (Exception ex) {
                    ex.printStackTrace();
                    showError("错误", "头像上传失败");
                }
            }
        });

        grid.add(new Label("用户名:"), 0, 0);
        grid.add(usernameField, 1, 0);
        grid.add(new Label("密码:"), 0, 1);
        grid.add(passwordField, 1, 1);
        grid.add(new Label("确认密码:"), 0, 2);
        grid.add(confirmPasswordField, 1, 2);
        grid.add(new Label("姓名:"), 0, 3);
        grid.add(nameField, 1, 3);
        grid.add(new Label("头像:"), 0, 4);
        grid.add(avatarView, 1, 4);
        grid.add(chooseImageBtn, 1, 5);

        dialog.getDialogPane().setContent(grid);
        dialog.getDialogPane().getButtonTypes().addAll(ButtonType.OK, ButtonType.CANCEL);

        dialog.setResultConverter(dialogButton -> {
            if (dialogButton == ButtonType.OK) {
                String username = usernameField.getText();
                String password = passwordField.getText();
                String confirmPassword = confirmPasswordField.getText();
                String name = nameField.getText();

                if (username.isEmpty() || password.isEmpty() || name.isEmpty()) {
                    showError("注册失败", "所有字段都必须填写");
                    return null;
                }

                if (!password.equals(confirmPassword)) {
                    showError("注册失败", "两次输入的密码不一致");
                    return null;
                }

                if (DatabaseManager.registerUser(username, password, name, avatarPath[0])) {
                    showInfo("注册成功", "请使用新账号登录");
                } else {
                    showError("注册失败", "用户名可能已存在");
                }
            }
            return null;
        });

        dialog.showAndWait();
    }

    private void showError(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.ERROR);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    private void showInfo(String title, String content) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setTitle(title);
        alert.setHeaderText(null);
        alert.setContentText(content);
        alert.showAndWait();
    }

    public void setOnLogin(Runnable onLoginSuccess) {
        this.onLoginSuccess = onLoginSuccess;
    }

    public String getUsername() {
        return currentUsername;
    }

    public String getPassword() {
        return passwordField.getText();
    }

    public Parent getView() {
        return root;
    }
} 